import React, { useEffect, useState, useRef } from 'react';
import { uniqueId } from 'lodash';

import { BaseSettingContext, defaultBaseSetting } from '@/pages/SalaryManage/constant/BaseSettingContext';
import { queryBaseSettingInfo } from '@/services/salaryManage/salaryCalculate';
import { defaultFormatResult } from '@/hooks';
import eventBus from '@/utils/eventBus';

/**
 * 基础数据提供控件，注setting与organizationCode只能传其中一个
 * @param setting 基础设置数据
 * @param organizationCode 行政机构编码
 * @param children
 * @returns {JSX.Element}
 * @constructor
 */
const BaseSettingProvider = ({ setting, organizationCode, children }) => {
    const [baseSetting, setBaseSetting] = useState(defaultBaseSetting);
    const [taskId, forceUpdate] = useState('');
    const preRef = useRef(null);

    if (setting && organizationCode) {
        console.error('BaseSettingProvider控件setting与organizationCode两者只能传一个值');
    }

    useEffect(() => {
        let isUnmount = false;
        preRef.current = organizationCode;
        if (organizationCode) {
            queryBaseSettingInfo(organizationCode)
                .then(defaultFormatResult.formatResult)
                .then(baseSettingData => {
                    // 处理warning，Can't perform a React state update on an unmounted component，判断isUnmount才去更新数据渲染组件
                    if (!isUnmount) {
                        setBaseSetting(baseSettingData);
                    }
                });
        }
        return () => {
            isUnmount = true;
        };
    }, [organizationCode, taskId]);

    useEffect(() => {
        if (setting) {
            setBaseSetting(setting);
        }
    }, [setting]);

    useEffect(() => {
        const handleUpdate = selectOrgCode => {
            if (selectOrgCode === organizationCode) {
                forceUpdate(uniqueId());
            }
        };
        eventBus.addListener('finance.baseSetting', handleUpdate);

        return () => eventBus.removeListener(handleUpdate);
    }, [organizationCode]);

    return (
        <BaseSettingContext.Provider value={{ baseSetting, setBaseSetting }}>{children}</BaseSettingContext.Provider>
    );
};

export default BaseSettingProvider;
